

import React, { useState, useEffect, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import Header from '../../components/Header';

interface UserProfileData {
  id?: string;
  userName: string;
  userAvatar: string | null;
  userProfile: string | null;
  userRole?: string;
  createTime?: string;
  // 保留原有字段用于兼容
  nickname?: string;
  gender?: 'male' | 'female' | 'other';
  bio?: string;
  avatar?: string;
}

const UserProfilePage: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<string>('basic');
  const [showPasswordModal, setShowPasswordModal] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isLogoutLoading, setIsLogoutLoading] = useState<boolean>(false);
  const [userProfileData, setUserProfileData] = useState<UserProfileData>({
    userName: '加载中...',
    userAvatar: null,
    userProfile: null,
    // 兼容字段
    nickname: '加载中...',
    gender: 'male',
    bio: '加载中...',
    avatar: 'https://s.coze.cn/image/eSbV8sZ4zMY/'
  });
  const [originalProfileData, setOriginalProfileData] = useState<UserProfileData>(userProfileData);
  const [passwordFormData, setPasswordFormData] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });
  
  const avatarInputRef = useRef<HTMLInputElement>(null);

  // 获取用户信息
  const fetchUserProfile = async () => {
    try {
      // 从localStorage或sessionStorage获取用户ID
      const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo');
      let userId = null;
      
      if (userInfo) {
        try {
          const parsedUserInfo = JSON.parse(userInfo);
          userId = parsedUserInfo.id;
        } catch (e) {
          console.error('解析用户信息失败:', e);
        }
      }

      // 如果没有用户ID，跳转到登录页面
      if (!userId) {
        console.warn('未找到用户ID，跳转到登录页面');
        navigate('/login');
        return;
      }

      const response = await fetch(`http://localhost:8121/api/user/get/vo?id=${userId}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include' // 包含cookies，用于session管理
      });

      const result = await response.json();

      if (response.ok && result.code === 0 && result.data) {
        const userData = result.data;
        const newProfileData: UserProfileData = {
          id: userData.id,
          userName: userData.userName || '未设置昵称',
          userAvatar: userData.userAvatar,
          userProfile: userData.userProfile,
          userRole: userData.userRole,
          createTime: userData.createTime,
          // 兼容字段
          nickname: userData.userName || '未设置昵称',
          bio: userData.userProfile || '这个人很懒，什么都没有留下...',
          avatar: userData.userAvatar || 'https://s.coze.cn/image/eSbV8sZ4zMY/',
          gender: 'male' // 默认值，因为后端没有这个字段
        };
        
        setUserProfileData(newProfileData);
        setOriginalProfileData(newProfileData);
      } else {
        console.error('获取用户信息失败:', result.message);
        // 可以显示错误信息或使用默认数据
      }
    } catch (error) {
      console.error('获取用户信息请求失败:', error);
      // 可以显示错误信息或使用默认数据
    }
  };

  useEffect(() => {
    const originalTitle = document.title;
    document.title = '个人中心 - 精进坊';
    
    // 获取用户信息
    fetchUserProfile();
    
    return () => { document.title = originalTitle; };
  }, []);

  const handleTabSwitch = (tabId: string) => {
    setActiveTab(tabId);
    
    // 处理收藏和历史标签页的跳转
    if (tabId === 'collections') {
      setTimeout(() => {
        navigate('/user-collections');
      }, 300);
    } else if (tabId === 'history') {
      setTimeout(() => {
        navigate('/user-history');
      }, 300);
    }
  };

  const handleAvatarUpload = () => {
    if (avatarInputRef.current) {
      avatarInputRef.current.click();
    }
  };

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        if (e.target?.result) {
          const newAvatar = e.target!.result as string;
          setUserProfileData(prev => ({
            ...prev,
            avatar: newAvatar,
            userAvatar: newAvatar
          }));
        }
      };
      reader.readAsDataURL(file);
    }
  };

  const handleProfileFormSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    setIsLoading(true);
    
    try {
      // 准备要提交的数据
      const updateData = {
        id: userProfileData.id,
        userName: userProfileData.nickname || userProfileData.userName,
        userProfile: userProfileData.bio || userProfileData.userProfile,
        userAvatar: userProfileData.avatar || userProfileData.userAvatar
      };

      // 这里可以调用更新用户信息的API
      // const response = await fetch('http://localhost:8121/api/user/update', {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json',
      //   },
      //   credentials: 'include',
      //   body: JSON.stringify(updateData)
      // });

      // const result = await response.json();

      // if (response.ok && result.code === 0) {
      //   setOriginalProfileData(userProfileData);
      //   alert('个人资料修改成功！');
      // } else {
      //   alert(result.message || '修改失败，请重试');
      // }

      // 暂时使用模拟更新
      setTimeout(() => {
        setIsLoading(false);
        setOriginalProfileData(userProfileData);
        alert('个人资料修改成功！');
      }, 1000);
      
    } catch (error) {
      console.error('更新个人资料失败:', error);
      alert('网络错误，请稍后重试');
      setIsLoading(false);
    }
  };

  const handleProfileFormCancel = () => {
    setUserProfileData(originalProfileData);
  };

  const handlePasswordModalOpen = () => {
    setShowPasswordModal(true);
  };

  const handlePasswordModalClose = () => {
    setShowPasswordModal(false);
    setPasswordFormData({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
  };

  const handlePasswordFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!passwordFormData.oldPassword || !passwordFormData.newPassword || !passwordFormData.confirmPassword) {
      alert('请填写完整的密码信息');
      return;
    }
    
    if (passwordFormData.newPassword !== passwordFormData.confirmPassword) {
      alert('两次输入的新密码不一致');
      return;
    }
    
    if (passwordFormData.newPassword.length < 6) {
      alert('新密码长度不能少于6位');
      return;
    }
    
    setIsLoading(true);
    
    setTimeout(() => {
      setIsLoading(false);
      handlePasswordModalClose();
      alert('密码修改成功！');
    }, 1000);
  };

  const handlePasswordModalBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      handlePasswordModalClose();
    }
  };

  // 退出登录函数
  const handleLogout = async () => {
    if (!confirm('确定要退出登录吗？')) {
      return;
    }

    setIsLogoutLoading(true);

    try {
      // 调用后端退出登录接口
      const response = await fetch('http://localhost:8121/api/user/logout', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include' // 包含cookies，用于session管理
      });

      const result = await response.json();

      if (response.ok && result.code === 0) {
        // 清除本地存储的用户信息
        localStorage.removeItem('userInfo');
        sessionStorage.removeItem('userInfo');
        
        // 清除其他可能的用户相关数据
        localStorage.removeItem('token');
        sessionStorage.removeItem('token');

        // 跳转到登录页面
        navigate('/login', { replace: true });
      } else {
        alert(result.message || '退出登录失败，请重试');
      }
    } catch (error) {
      console.error('退出登录请求失败:', error);
      alert('网络错误，请稍后重试');
    } finally {
      setIsLogoutLoading(false);
    }
  };

  const handleContinueLearning = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}`);
  };

  const handleRemoveCollection = (collectionId: string) => {
    // 实现取消收藏逻辑
    console.log('取消收藏:', collectionId);
    alert('取消收藏成功！');
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 头部栏 */}
      <Header currentPage="" />

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">个人中心</h2>
                <nav className="text-sm text-text-secondary">
                  <span>首页</span>
                  <i className="fas fa-chevron-right mx-2"></i>
                  <span>个人中心</span>
                </nav>
              </div>
            </div>
          </div>

          {/* 标签页导航 */}
          <div className="mb-6">
            <div className="flex space-x-4" role="tablist">
              <button 
                onClick={() => handleTabSwitch('basic')}
                className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${activeTab === 'basic' ? styles.tabActive : styles.tabInactive}`}
                role="tab" 
                aria-controls="basic-content"
              >
                基本资料
              </button>
              <button 
                onClick={() => handleTabSwitch('security')}
                className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${activeTab === 'security' ? styles.tabActive : styles.tabInactive}`}
                role="tab" 
                aria-controls="security-content"
              >
                账号安全
              </button>
              <button 
                onClick={() => handleTabSwitch('data')}
                className={`px-6 py-3 text-sm font-medium rounded-lg focus:outline-none ${activeTab === 'data' ? styles.tabActive : styles.tabInactive}`}
                role="tab" 
                aria-controls="data-content"
              >
                学习数据
              </button>

              {/* 退出登录按钮 */}
              <button 
                onClick={handleLogout}
                disabled={isLogoutLoading}
                className="px-6 py-3 text-sm font-medium rounded-lg focus:outline-none bg-red-50 text-red-600 hover:bg-red-100 disabled:opacity-50 disabled:cursor-not-allowed ml-auto"
              >
                {isLogoutLoading ? (
                  <>
                    <i className="fas fa-spinner fa-spin mr-2"></i>
                    退出中...
                  </>
                ) : (
                  <>
                    <i className="fas fa-sign-out-alt mr-2"></i>
                    退出登录
                  </>
                )}
              </button>
            </div>
          </div>

          {/* 标签页内容 */}
          <div>
            {/* 基本资料 */}
            {activeTab === 'basic' && (
              <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                <h3 className="text-lg font-semibold text-text-primary mb-6">基本资料</h3>
                <form onSubmit={handleProfileFormSubmit} className="space-y-6">
                  {/* 头像上传 */}
                  <div className="flex items-center space-x-6">
                    <div className="relative">
                      <img 
                        src={userProfileData.avatar}
                        alt="用户头像" 
                        className="w-20 h-20 rounded-full object-cover" 
                        data-category="人物"
                      />
                      <button 
                        type="button" 
                        onClick={handleAvatarUpload}
                        className="absolute -bottom-1 -right-1 w-6 h-6 bg-secondary text-white rounded-full flex items-center justify-center text-xs hover:bg-accent"
                      >
                        <i className="fas fa-camera"></i>
                      </button>
                      <input 
                        type="file" 
                        ref={avatarInputRef}
                        onChange={handleAvatarChange}
                        accept="image/*" 
                        className="hidden"
                      />
                    </div>
                    <div>
                      <button 
                        type="button" 
                        onClick={handleAvatarUpload}
                        className="px-4 py-2 bg-gray-100 text-text-secondary rounded-lg hover:bg-gray-200"
                      >
                        更换头像
                      </button>
                      <p className="text-sm text-text-secondary mt-1">支持JPG、PNG格式，文件大小不超过2MB</p>
                    </div>
                  </div>

                  {/* 昵称 */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label htmlFor="nickname" className="block text-sm font-medium text-text-primary">昵称</label>
                      <input 
                        type="text" 
                        id="nickname" 
                        name="nickname" 
                        value={userProfileData.nickname || ''}
                        onChange={(e) => setUserProfileData(prev => ({ 
                          ...prev, 
                          nickname: e.target.value,
                          userName: e.target.value
                        }))}
                        className={`w-full px-4 py-3 border border-gray-200 rounded-lg ${styles.formInputFocus}`}
                        placeholder="请输入昵称"
                      />
                    </div>

                    {/* 性别 */}
                    <div className="space-y-2">
                      <label className="block text-sm font-medium text-text-primary">性别</label>
                      <div className="flex space-x-4">
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="male" 
                            checked={userProfileData.gender === 'male'}
                            onChange={(e) => setUserProfileData(prev => ({ ...prev, gender: e.target.value as 'male' | 'female' | 'other' }))}
                            className="text-secondary focus:ring-secondary"
                          />
                          <span className="text-text-secondary">男</span>
                        </label>
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="female"
                            checked={userProfileData.gender === 'female'}
                            onChange={(e) => setUserProfileData(prev => ({ ...prev, gender: e.target.value as 'male' | 'female' | 'other' }))}
                            className="text-secondary focus:ring-secondary"
                          />
                          <span className="text-text-secondary">女</span>
                        </label>
                        <label className="flex items-center space-x-2 cursor-pointer">
                          <input 
                            type="radio" 
                            name="gender" 
                            value="other"
                            checked={userProfileData.gender === 'other'}
                            onChange={(e) => setUserProfileData(prev => ({ ...prev, gender: e.target.value as 'male' | 'female' | 'other' }))}
                            className="text-secondary focus:ring-secondary"
                          />
                          <span className="text-text-secondary">其他</span>
                        </label>
                      </div>
                    </div>
                  </div>

                  {/* 简介 */}
                  <div className="space-y-2">
                    <label htmlFor="bio" className="block text-sm font-medium text-text-primary">个人简介</label>
                    <textarea 
                      id="bio" 
                      name="bio" 
                      rows={4}
                      value={userProfileData.bio || ''}
                      onChange={(e) => setUserProfileData(prev => ({ 
                        ...prev, 
                        bio: e.target.value,
                        userProfile: e.target.value
                      }))}
                      className={`w-full px-4 py-3 border border-gray-200 rounded-lg ${styles.formInputFocus} resize-none`}
                      placeholder="介绍一下自己吧..."
                    />
                  </div>

                  {/* 保存按钮 */}
                  <div className="flex justify-end space-x-4 pt-4">
                    <button 
                      type="button" 
                      onClick={handleProfileFormCancel}
                      className="px-6 py-3 bg-gray-100 text-text-secondary rounded-lg hover:bg-gray-200"
                    >
                      取消
                    </button>
                    <button 
                      type="submit" 
                      disabled={isLoading}
                      className="px-6 py-3 bg-secondary text-white rounded-lg hover:bg-accent disabled:opacity-50"
                    >
                      {isLoading ? '保存中...' : '保存修改'}
                    </button>
                  </div>
                </form>
              </div>
            )}

            {/* 账号安全 */}
            {activeTab === 'security' && (
              <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                <h3 className="text-lg font-semibold text-text-primary mb-6">账号安全</h3>
                
                <div className="space-y-6">
                  {/* 修改密码 */}
                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 bg-red-100 rounded-lg flex items-center justify-center">
                        <i className="fas fa-lock text-red-500"></i>
                      </div>
                      <div>
                        <h4 className="font-medium text-text-primary">修改密码</h4>
                        <p className="text-sm text-text-secondary">定期更换密码，保护账号安全</p>
                      </div>
                    </div>
                    <button 
                      onClick={handlePasswordModalOpen}
                      className="px-4 py-2 bg-gray-200 text-text-secondary rounded-lg hover:bg-gray-300"
                    >
                      修改
                    </button>
                  </div>

                  {/* 绑定邮箱 */}
                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                        <i className="fas fa-envelope text-blue-500"></i>
                      </div>
                      <div>
                        <h4 className="font-medium text-text-primary">绑定邮箱</h4>
                        <p className="text-sm text-text-secondary">zhang***@example.com</p>
                      </div>
                    </div>
                    <span className="px-3 py-1 bg-green-100 text-green-600 rounded-full text-sm">已绑定</span>
                  </div>

                  {/* 绑定手机 */}
                  <div className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                    <div className="flex items-center space-x-4">
                      <div className="w-10 h-10 bg-green-100 rounded-lg flex items-center justify-center">
                        <i className="fas fa-mobile-alt text-green-500"></i>
                      </div>
                      <div>
                        <h4 className="font-medium text-text-primary">绑定手机</h4>
                        <p className="text-sm text-text-secondary">138****5678</p>
                      </div>
                    </div>
                    <span className="px-3 py-1 bg-green-100 text-green-600 rounded-full text-sm">已绑定</span>
                  </div>
                </div>
              </div>
            )}

            {/* 学习数据 */}
            {activeTab === 'data' && (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* 学习统计 */}
                <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                  <h3 className="text-lg font-semibold text-text-primary mb-6">学习统计</h3>
                  
                  <div className="space-y-6">
                    {/* 学习时长 */}
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-text-primary">总学习时长</h4>
                        <p className="text-2xl font-bold text-secondary mt-1">156小时</p>
                      </div>
                      <div className="w-16 h-16 bg-primary rounded-full flex items-center justify-center">
                        <i className="fas fa-clock text-secondary text-2xl"></i>
                      </div>
                    </div>

                    {/* 完成课程 */}
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-text-primary">完成课程</h4>
                        <p className="text-2xl font-bold text-accent mt-1">23门</p>
                      </div>
                      <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center">
                        <i className="fas fa-check-circle text-green-500 text-2xl"></i>
                      </div>
                    </div>

                    {/* 收藏内容 */}
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-text-primary">收藏内容</h4>
                        <p className="text-2xl font-bold text-purple-500 mt-1">47个</p>
                      </div>
                      <div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center">
                        <i className="fas fa-heart text-purple-500 text-2xl"></i>
                      </div>
                    </div>

                    {/* 连续学习天数 */}
                    <div className="flex items-center justify-between">
                      <div>
                        <h4 className="font-medium text-text-primary">连续学习</h4>
                        <p className="text-2xl font-bold text-orange-500 mt-1">7天</p>
                      </div>
                      <div className="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center">
                        <i className="fas fa-fire text-orange-500 text-2xl"></i>
                      </div>
                    </div>
                  </div>
                </div>

                {/* 学习进度 */}
                <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                  <h3 className="text-lg font-semibold text-text-primary mb-6">本月学习进度</h3>
                  
                  <div className="space-y-6">
                    {/* 月度目标 */}
                    <div>
                      <div className="flex justify-between items-center mb-2">
                        <span className="text-sm font-medium text-text-primary">月度目标</span>
                        <span className="text-sm text-text-secondary">15/20小时</span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div className={`${styles.progressBar} h-2 rounded-full`} style={{width: '75%'}}></div>
                      </div>
                    </div>

                    {/* 板块学习分布 */}
                    <div>
                      <h4 className="text-sm font-medium text-text-primary mb-3">板块学习分布</h4>
                      <div className="space-y-3">
                        <div className="flex justify-between items-center">
                          <div className="flex items-center space-x-2">
                            <div className="w-3 h-3 bg-secondary rounded-full"></div>
                            <span className="text-sm text-text-secondary">认知提升</span>
                          </div>
                          <span className="text-sm font-medium text-text-primary">45%</span>
                        </div>
                        <div className="flex justify-between items-center">
                          <div className="flex items-center space-x-2">
                            <div className="w-3 h-3 bg-green-500 rounded-full"></div>
                            <span className="text-sm text-text-secondary">身体健身</span>
                          </div>
                          <span className="text-sm font-medium text-text-primary">30%</span>
                        </div>
                        <div className="flex justify-between items-center">
                          <div className="flex items-center space-x-2">
                            <div className="w-3 h-3 bg-purple-500 rounded-full"></div>
                            <span className="text-sm text-text-secondary">学习能力</span>
                          </div>
                          <span className="text-sm font-medium text-text-primary">25%</span>
                        </div>
                      </div>
                    </div>

                    {/* 本周学习 */}
                    <div>
                      <h4 className="text-sm font-medium text-text-primary mb-3">本周学习</h4>
                      <div className="grid grid-cols-7 gap-2 text-center">
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周一</div>
                          <div className="w-8 h-8 bg-secondary rounded-lg flex items-center justify-center">
                            <span className="text-xs text-white font-medium">2h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周二</div>
                          <div className="w-8 h-8 bg-secondary rounded-lg flex items-center justify-center">
                            <span className="text-xs text-white font-medium">1h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周三</div>
                          <div className="w-8 h-8 bg-gray-200 rounded-lg flex items-center justify-center">
                            <span className="text-xs text-text-secondary">0h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周四</div>
                          <div className="w-8 h-8 bg-secondary rounded-lg flex items-center justify-center">
                            <span className="text-xs text-white font-medium">3h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周五</div>
                          <div className="w-8 h-8 bg-secondary rounded-lg flex items-center justify-center">
                            <span className="text-xs text-white font-medium">2h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周六</div>
                          <div className="w-8 h-8 bg-secondary rounded-lg flex items-center justify-center">
                            <span className="text-xs text-white font-medium">4h</span>
                          </div>
                        </div>
                        <div className="space-y-1">
                          <div className="text-xs text-text-secondary">周日</div>
                          <div className="w-8 h-8 bg-gray-200 rounded-lg flex items-center justify-center">
                            <span className="text-xs text-text-secondary">0h</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* 我的收藏 */}
            {activeTab === 'collections' && (
              <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-lg font-semibold text-text-primary">我的收藏</h3>
                  <Link to="/user-collections" className="text-secondary hover:text-accent text-sm font-medium">
                    查看全部 <i className="fas fa-arrow-right ml-1"></i>
                  </Link>
                </div>
                
                <div className="space-y-4">
                  {/* 收藏内容项1 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/xCGrtFiA9EE/" 
                      alt="收藏内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="商业科技"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-secondary text-white px-2 py-1 rounded-full text-xs">认知提升</span>
                        <span className="text-xs text-text-secondary">收藏于 2天前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">批判性思维：如何建立理性思考框架</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。</p>
                    </div>
                    <button 
                      onClick={() => handleRemoveCollection('1')}
                      className="text-red-500 hover:text-red-600"
                    >
                      <i className="fas fa-heart-broken"></i>
                    </button>
                  </div>

                  {/* 收藏内容项2 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/10jmEqgt0ww/" 
                      alt="收藏内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="运动体育"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-green-500 text-white px-2 py-1 rounded-full text-xs">身体健身</span>
                        <span className="text-xs text-text-secondary">收藏于 1周前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">30天全身训练计划：从零开始塑造完美身材</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">科学的训练计划，适合初学者的全身锻炼方案，帮助你建立运动习惯。</p>
                    </div>
                    <button 
                      onClick={() => handleRemoveCollection('2')}
                      className="text-red-500 hover:text-red-600"
                    >
                      <i className="fas fa-heart-broken"></i>
                    </button>
                  </div>

                  {/* 收藏内容项3 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/GNXxDhM3yDI/" 
                      alt="收藏内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="商业科技"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-purple-500 text-white px-2 py-1 rounded-full text-xs">学习能力</span>
                        <span className="text-xs text-text-secondary">收藏于 2周前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">费曼学习法：如何快速掌握新知识</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">通过费曼技巧，学会用简单的语言解释复杂概念，加深理解和记忆。</p>
                    </div>
                    <button 
                      onClick={() => handleRemoveCollection('3')}
                      className="text-red-500 hover:text-red-600"
                    >
                      <i className="fas fa-heart-broken"></i>
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* 学习历史 */}
            {activeTab === 'history' && (
              <div className={`${styles.contentCard} rounded-card shadow-card p-6`}>
                <div className="flex items-center justify-between mb-6">
                  <h3 className="text-lg font-semibold text-text-primary">学习历史</h3>
                  <Link to="/user-history" className="text-secondary hover:text-accent text-sm font-medium">
                    查看全部 <i className="fas fa-arrow-right ml-1"></i>
                  </Link>
                </div>
                
                <div className="space-y-4">
                  {/* 学习历史项1 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/dK3h3ErAFTQ/" 
                      alt="学习内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="商业科技"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-secondary text-white px-2 py-1 rounded-full text-xs">认知提升</span>
                        <span className="text-xs text-text-secondary">上次学习：今天 14:30</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">如何运用第一性原理进行创新思考</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">深度解析埃隆·马斯克的思维模式，学会从根本上解决问题的方法。</p>
                      <div className="flex items-center justify-between mt-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-20 bg-gray-200 rounded-full h-1">
                            <div className="bg-secondary h-1 rounded-full" style={{width: '60%'}}></div>
                          </div>
                          <span className="text-xs text-text-secondary">60%</span>
                        </div>
                        <button 
                          onClick={() => handleContinueLearning('1')}
                          className="px-3 py-1 bg-secondary text-white rounded-lg text-xs hover:bg-accent"
                        >
                          继续学习
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* 学习历史项2 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/WFrOThWCd-4/" 
                      alt="学习内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="运动体育"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-green-500 text-white px-2 py-1 rounded-full text-xs">身体健身</span>
                        <span className="text-xs text-text-secondary">上次学习：昨天 19:45</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">HIIT高强度间歇训练的科学原理</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">了解HIIT训练的生理机制，制定高效的燃脂计划。</p>
                      <div className="flex items-center justify-between mt-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-20 bg-gray-200 rounded-full h-1">
                            <div className="bg-green-500 h-1 rounded-full" style={{width: '100%'}}></div>
                          </div>
                          <span className="text-xs text-green-500">已完成</span>
                        </div>
                        <button className="px-3 py-1 bg-gray-200 text-text-secondary rounded-lg text-xs">
                          重新学习
                        </button>
                      </div>
                    </div>
                  </div>

                  {/* 学习历史项3 */}
                  <div className="flex space-x-4 p-4 bg-gray-50 rounded-lg">
                    <img 
                      src="https://s.coze.cn/image/Q9izBWa7GtI/" 
                      alt="学习内容缩略图" 
                      className="w-16 h-16 object-cover rounded-lg" 
                      data-category="商业科技"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-purple-500 text-white px-2 py-1 rounded-full text-xs">学习能力</span>
                        <span className="text-xs text-text-secondary">上次学习：3天前 10:20</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1">番茄工作法：提升专注力的实用技巧</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">掌握时间管理的核心方法，告别拖延症，提高工作效率。</p>
                      <div className="flex items-center justify-between mt-2">
                        <div className="flex items-center space-x-2">
                          <div className="w-20 bg-gray-200 rounded-full h-1">
                            <div className="bg-purple-500 h-1 rounded-full" style={{width: '30%'}}></div>
                          </div>
                          <span className="text-xs text-text-secondary">30%</span>
                        </div>
                        <button 
                          onClick={() => handleContinueLearning('3')}
                          className="px-3 py-1 bg-secondary text-white rounded-lg text-xs hover:bg-accent"
                        >
                          继续学习
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </main>
      </div>

      {/* 修改密码弹窗 */}
      {showPasswordModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
          onClick={handlePasswordModalBackdropClick}
        >
          <div className="bg-white rounded-card shadow-card p-6 w-full max-w-md mx-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold text-text-primary">修改密码</h3>
              <button 
                onClick={handlePasswordModalClose}
                className="text-gray-400 hover:text-gray-600"
              >
                <i className="fas fa-times"></i>
              </button>
            </div>
            
            <form onSubmit={handlePasswordFormSubmit} className="space-y-4">
              <div className="space-y-2">
                <label htmlFor="old-password" className="block text-sm font-medium text-text-primary">当前密码</label>
                <input 
                  type="password" 
                  id="old-password" 
                  name="old-password"
                  value={passwordFormData.oldPassword}
                  onChange={(e) => setPasswordFormData(prev => ({ ...prev, oldPassword: e.target.value }))}
                  className={`w-full px-4 py-3 border border-gray-200 rounded-lg ${styles.formInputFocus}`}
                  placeholder="请输入当前密码"
                />
              </div>
              
              <div className="space-y-2">
                <label htmlFor="new-password" className="block text-sm font-medium text-text-primary">新密码</label>
                <input 
                  type="password" 
                  id="new-password" 
                  name="new-password"
                  value={passwordFormData.newPassword}
                  onChange={(e) => setPasswordFormData(prev => ({ ...prev, newPassword: e.target.value }))}
                  className={`w-full px-4 py-3 border border-gray-200 rounded-lg ${styles.formInputFocus}`}
                  placeholder="请输入新密码"
                />
              </div>
              
              <div className="space-y-2">
                <label htmlFor="confirm-password" className="block text-sm font-medium text-text-primary">确认新密码</label>
                <input 
                  type="password" 
                  id="confirm-password" 
                  name="confirm-password"
                  value={passwordFormData.confirmPassword}
                  onChange={(e) => setPasswordFormData(prev => ({ ...prev, confirmPassword: e.target.value }))}
                  className={`w-full px-4 py-3 border border-gray-200 rounded-lg ${styles.formInputFocus}`}
                  placeholder="请再次输入新密码"
                />
              </div>
              
              <div className="flex space-x-3 pt-4">
                <button 
                  type="button" 
                  onClick={handlePasswordModalClose}
                  className="flex-1 py-3 bg-gray-100 text-text-secondary rounded-lg hover:bg-gray-200"
                >
                  取消
                </button>
                <button 
                  type="submit" 
                  disabled={isLoading}
                  className="flex-1 py-3 bg-secondary text-white rounded-lg hover:bg-accent disabled:opacity-50"
                >
                  {isLoading ? '修改中...' : '确认修改'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserProfilePage;

